import { ref } from "vue";
import { submitBillData, uploadBillImage } from "../../api/modules/bill.api";
import {Bill} from "../../types/bill";



export function useHomePage() {
    const bills = ref<Bill[]>([]);
    // 修改为支持多个文件
    const selectedFiles = ref<File[]>([]);
    const isLoading = ref(false);

    // Modal 状态
    const modalVisible = ref(false);
    const modalTitle = ref("提示");
    const modalMessage = ref("");

    function showModal(message: string, title: string = "提示") {
        modalMessage.value = message;
        modalTitle.value = title;
        modalVisible.value = true;
    }

    function closeModal() {
        modalVisible.value = false;
    }

    const handleFileUpload = (event: Event): void => {
        const target = event.target as HTMLInputElement;
        if (target.files && target.files.length > 0) {
            // 将 FileList 转换为数组
            selectedFiles.value = Array.from(target.files);
        }
    };

    const uploadImage = async (): Promise<void> => {
        if (!selectedFiles.value.length) return;
        isLoading.value = true;
        const formData = new FormData();
        // 遍历所有文件, 使用字段名 "files"
        selectedFiles.value.forEach((file) => {
            formData.append("files", file);
        });

        try {
            const result = await uploadBillImage(formData);
            if (result.success && result.data) {
                if (result.data.bills && Array.isArray(result.data.bills)) {
                    bills.value = result.data.bills;
                } else if (result.data.raw) {
                    showModal("图像识别返回的内容无法解析为 JSON：" + result.data.raw);
                } else if (result.data.error) {
                    showModal("识别时出现错误：" + result.data.message);
                }
                // 上传成功后清空已选择的文件列表
                selectedFiles.value = [];
            } else {
                showModal("接口调用失败：未知错误");
            }
        } catch (error: any) {
            console.error("上传异常", error);
            showModal("网络异常，请重试");
        } finally {
            isLoading.value = false;
        }
    };

    const deleteBill = (index: number): void => {
        bills.value.splice(index, 1);
    };

    const submitBills = async (): Promise<void> => {
        if (bills.value.length === 0) {
            showModal("没有可提交的账单！");
            return;
        }
        isLoading.value = true;
        try {
            await submitBillData(bills.value);
            showModal("账单提交成功！", "成功");
            bills.value = []; // 清空账单列表
        } catch (error: any) {
            console.error("提交异常", error);
            showModal("网络异常，请重试");
        } finally {
            isLoading.value = false;
        }
    };

    return {
        bills,
        selectedFiles,
        handleFileUpload,
        uploadImage,
        deleteBill,
        submitBills,
        isLoading,
        modalVisible,
        modalTitle,
        modalMessage,
        closeModal,
    };
}